package blue.mqtt4j.internal.client.impl;

import blue.mqtt4j.client.MqttMessage;
import blue.mqtt4j.client.MqttQoS;
import blue.mqtt4j.core.util.AssertUtil;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.mqtt.MqttPublishMessage;

/**
 * @author Jin Zheng
 * @since 1.0 2020-10-16
 */
public class DefaultMqttMessage implements MqttMessage
{
	private String topic;
	private MqttQoS qos;
	private Object payload;

	public DefaultMqttMessage(String topic, Object payload)
	{
		this(topic, MqttMessage.DEFAULT_QOS, payload);
	}

	public DefaultMqttMessage(String topic, MqttQoS qos, Object payload)
	{
		AssertUtil.isEmpty(topic, "Topic");
		AssertUtil.isNull(qos, "QoS");
		AssertUtil.isNull(payload, "Payload");
		this.topic = topic;
		this.qos = qos;
		this.payload = payload;
	}

	public DefaultMqttMessage(MqttPublishMessage message)
	{
		this.topic = message.variableHeader().topicName();
		this.qos = MqttQoS.valueOf(message.fixedHeader().qosLevel());
		byte[] bytes = ByteBufUtil.getBytes(message.payload());
		this.payload = bytes;
	}

	@Override
	public String topic()
	{
		return topic;
	}

	@Override
	public MqttQoS qos()
	{
		return qos;
	}

	@Override
	public Object payload()
	{
		return payload;
	}

	@Override
	public String toString()
	{
		return String.format("MqttMessage{topic: %s, qos: %s, payload: %s}", topic, qos, payload);
	}
}

